<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" >
      <el-form-item label="菜品名称" prop="name" v-show="showSearch">
        <el-input v-model="queryParams.name" placeholder="请输入菜品名称" clearable style="width: 240px" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item v-show="showSearch">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
<!--      <el-form-item >-->
<!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
<!--      </el-form-item>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-form>
    <el-table v-loading="loading" :data="rowList">
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="菜品编号" prop="id" width="120" align="center" fixed="left"/>
      <el-table-column label="菜品名称" prop="name" width="120" align="center"/>
<!--      <el-table-column label="审核状态" prop="approveStatus" width="160" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <span @click="handleApprove(scope.row)" :style="{'color': colors(scope.row.approveStatus), 'cursor': 'pointer'}">{{ scope.row.approveStatus }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="启用"
            inactive-value="停用"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="菜品图片" prop="image" align="center" :width="imageColWidth">
        <template v-slot:default="scope">
          <image-preview v-for="(item,index) in scope.row.images"
                    style="width: 100px; height: 100px; margin-right: 15px"
                    :src="item">
          </image-preview>
        </template>
      </el-table-column>
      <el-table-column label="口味" prop="taste" width="120" align="center"/>
      <el-table-column label="类型" prop="hot" width="120" align="center"/>
      <el-table-column label="荤素" prop="hun" width="120" align="center"/>
      <el-table-column label="创建人" prop="createBy" width="120" align="center"/>
      <el-table-column label="更新人" prop="updateBy" width="120" align="center"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="130">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleDetail(scope.row)"-->
<!--          >明细</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜品配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="菜品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入菜品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
        <el-form-item label="类型" prop="hot">
          <!-- <el-input v-model="form.hot" placeholder="请输入凉热" /> -->
           <el-select v-model="form.hot" placeholder="请选择菜品类型" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in hotOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="荤素" prop="status">
          <!-- <el-input v-model="form.hun" placeholder="请输入荤素" /> -->
           <el-select v-model="form.hun" placeholder="请选择菜品荤素" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in meatOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="口味" prop="taste">
          <!-- <el-input v-model="form.taste" placeholder="请输入菜品口味" /> -->
          <el-select v-model="form.taste" placeholder="请选择菜品口味" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in tasteOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>

        </el-form-item>
      </el-col>
      </el-row>
      <el-form-item label="上传图片" prop="image" required>
        <ImageUpload
          v-model="form.image"
          :limit="3"/>
      </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, get, listAll, del, add, update } from "@/api/shop/base/base";
import { getDicts } from "@/api/system/dict/data";
export default {
  name: "Goods",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      imageColWidth: 150,
      // 菜品表格数据
      rowList: [],
      menuOptions: [],
      hotOptions: [],
      meatOptions: [],
      tasteOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      // 表单参数
      form: {
        hot:'热菜',
        hun:'荤菜',
        taste:'咸'
      },
      // 表单校验
      rules: {

      }
    };
  },
  created() {
    this.getList();
    this.getType('menu_status');
    this.getType('hotpc_status');
    this.getType('meat_status');
    this.getType('taste_status');
  },
  methods: {
    handleExport() {
      this.download('shop/base/base/export', {
        ...this.queryParams
      }, `base_${new Date().getTime()}.xlsx`)
    },
    handleApprove(row) {
      if (row.approveStatus === "未提交审批") {
        this.$modal.msgWarning("未提交审批");
      } else {
        this.$router.push("/approve/detail/" + row.approveMissionId);
      }
    },
    validateInputValue() {
      this.form.price = this.form.price.replace(/[^0-9.]/g, ""); // 只允许数字和小数点
      this.form.price = this.form.price.replace(/(\..*)\./g, "$1"); // 只允许一个小数点
    },
    async getType(type) {
      const {data} = await getDicts(type);
      let value;
      switch (type) {
        case 'menu_status':
        value =  'menuOptions'
          break;
        case 'hotpc_status':
        value =  'hotOptions'
          break;
        case 'meat_status':
        value =  'meatOptions'
          break;
        case 'taste_status':
        value =  'tasteOptions'
          break;
        default:
          break;
      }
      this[value] = data.map(item=>({label:item.dictLabel,value:item.dictValue}))
    },
    handleStatusChange(row) {
      let text = row.status === "启用" ? "启用" : "停用";
      update({
        id: row.id,
        status: row.status
      }).then(response => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        let maxWith = 1;
        for (var i = 0; i < response.rows.length; i++) {
          response.rows[i].images = [];
          if (response.rows[i].image != null && response.rows[i].image != undefined) {
            response.rows[i].images = response.rows[i].image.split(",");
          }
          if (response.rows[i].images.length > maxWith) {
            maxWith = response.rows[i].images.length;
          }
        }
        this.imageColWidth = maxWith * 150;
        this.rowList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form = {};
      this.form.image = "/profile/upload/2023/11/29/98f2f7ac42789d5e23e3cba321befd4.jpg";
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      get(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.status = "启用";
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name = row.name;
      this.$modal.confirm('是否确认删除名称为"' + name + '"的菜品？').then(function() {
        return del(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleDetail":
          this.handleDetail(row);
          break;
        default:
          break;
      }
    },
    handleDetail: function(row) {
      const id = row.id;
      this.$router.push("/shop/base/detail/" + id);
    },
    colors(status) {
      if (status === "通过") {
        return '#2a9c4a'
      } else if (status === "拒绝") {
        return '#FF0000'
      } else if (status === "审批中") {
        return '#fe9f29'
      } else {
        return '#fe9f29'
      }
    },
  }
};
</script>
